package megrez.keycloak.common;

import org.springframework.util.StringUtils;

import lombok.experimental.UtilityClass;
/**
 * 数据脱敏
 *  
 * @author Lucky Yang
 * @since 0.0.1
 */
@UtilityClass
public class DesensitizeHelper {
    private static final String EMPTY = "";

    public enum Rule {
        IDENTIFY_CODE("(?<=\\w{3})\\w(?=\\w{4})", "*"),
        PHONE_NUMBER("(?<=\\w{3})\\w(?=\\w{4})", "*"),
        EMAIL("(^\\w{2})[^@]*(@.*$)", "$1****$2")
        ;
        public final String regex;
        public final String desensilize;
        
        private Rule(String regex, String desensilize) {
            this.regex = regex;
            this.desensilize = desensilize;
        }
    }

    public String identifyCode(String identifyCode) {
        if (!StringUtils.hasText(identifyCode)) {
            return identifyCode;
        }

        if (identifyCode.length() < 7) {
            return EMPTY;
        }
        return identifyCode.replaceAll(Rule.IDENTIFY_CODE.regex, Rule.IDENTIFY_CODE.desensilize);
    }

    public String phoneNumber(String phoneNumber) {
        if (!StringUtils.hasText(phoneNumber)) {
            return phoneNumber;
        }

        if (phoneNumber.length() < 7) {
            return EMPTY;
        }

        return phoneNumber.replaceAll(Rule.PHONE_NUMBER.regex, Rule.PHONE_NUMBER.desensilize);
    }

    public String email(String email) {
        if (!StringUtils.hasText(email)) {
            return email;
        }

        return email.replaceAll(Rule.EMAIL.regex, Rule.EMAIL.desensilize);
    }
}
